package com.zdglf.mmd.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.zdglf.mmd.R;

import com.zdglf.mmd.model.PMDModel;
import com.zdglf.mmd.utils.FileUtils;
import com.zdglf.mmd.utils.OpenGLUtils;

import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;



public class GoPMDModelActivity extends BaseActivity implements GLSurfaceView.Renderer {

    private static final int MODEL_PARSE_SUCCESS = 1;
    private static final int MODEL_PARSE_FAIL = 2;
    private static final int MOTION_PARSE_SUCCESS = 3;
    private static final int MOTION_PARSE_FAIL = 4;
    private static final int MODEL_RENDER_FAIL = 5;

    RelativeLayout rl_main;
    long maxFrame = 0;
    GoPMDModelActivity activity;

    PMDModel pmdModel;
//    CubeModel pmdModel;
    GLSurfaceView surfaceView;
    ProgressDialog waitDialog;
    ExecutorService threadService = Executors.newCachedThreadPool();
    String directory;
    String fileName;

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            waitDialog.cancel();
            switch (msg.what) {
                case MODEL_PARSE_SUCCESS:
                    surfaceView = new GLSurfaceView(activity);
                    surfaceView.setEGLContextClientVersion(2);
                    surfaceView.setRenderer(activity);
                    rl_main.addView(surfaceView);
//                    StringBuilder dataBuilder = new StringBuilder();
//                    dataBuilder.append("名字：\n").append(miku.name).append("\n").append("批注：\n").append(miku.comment).append("\n");
//                    if(miku.english_flag!=0){
//                        dataBuilder.append("英文名字：\n").append(miku.name).append("\n").append("英文批注：\n").append(miku.comment).append("\n");
//                    }
//                    AlertDialog dialog = new AlertDialog.Builder(GoPMDModelActivity.this)
//                            .setTitle(R.string.mmd_model_info)
//                            .setMessage(dataBuilder.toString())
//                            .setPositiveButton(R.string.mmd_ok, null)
//                            .show();
//                    surfaceView.setOnTouchListener(modelTouchListener);
                    break;
                case MODEL_PARSE_FAIL:
                    Toast.makeText(activity, R.string.mmd_model_parse_fail, Toast.LENGTH_SHORT).show();
                case MODEL_RENDER_FAIL:
                    Toast.makeText(activity, R.string.mmd_render_fail, Toast.LENGTH_SHORT).show();
                    break;
                case MOTION_PARSE_SUCCESS:
                    break;
                case MOTION_PARSE_FAIL:

                    break;
            }
        }
    };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        activity = this;
        if(!OpenGLUtils.checkSupportOpenGL2(this)){
            Toast.makeText(this, R.string.mmd_not_support_opengl_2, Toast.LENGTH_LONG).show();
            finish();
        }

        initView();
        getIntentData();

    }

    private void getIntentData() {
        Intent it = getIntent();
        String path = it.getData().getPath();
        File f = new File(path);
        directory = f.getParent().toString();
        fileName = f.getName();
        waitDialog.show();

        pmdModel = new PMDModel();
//        pmdModel = new CubeModel();
        threadService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    if (pmdModel.loadFile(directory, fileName)){
                        handler.sendEmptyMessage(MODEL_PARSE_SUCCESS);
                    }else{
                        handler.sendEmptyMessage(MODEL_PARSE_FAIL);
                    }

                }catch (Exception e){
                    e.printStackTrace();
                    handler.sendEmptyMessage(MODEL_PARSE_FAIL);
                }

            }
        });
    }



    private void initView() {
        waitDialog = new ProgressDialog(this);
        waitDialog.setTitle(R.string.load_title);
        waitDialog.setMessage(getResources().getString(R.string.load_message));

        rl_main = (RelativeLayout)findViewById(R.id.rl_main);


    }

    @Override
    protected void onPause() {
        super.onPause();
        if(surfaceView!=null) {
            surfaceView.onPause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(surfaceView!=null) {
            surfaceView.onResume();
        }

    }

    @Override
    public void onSurfaceCreated(GL10 gl10, EGLConfig eglConfig) {
    }

    @Override
    public void onSurfaceChanged(GL10 gl10, int width, int height) {
        try {
            String fShader = FileUtils.readRawTextFile(this, R.raw.f);
            String vShader = FileUtils.readRawTextFile(this, R.raw.v);
//            String fShader = FileUtils.readRawTextFile(this, R.raw.color_fragment_shader);
//            String vShader = FileUtils.readRawTextFile(this, R.raw.color_vertex_shader);
            if (!pmdModel.initShader(vShader, fShader)){
                handler.sendEmptyMessage(MODEL_RENDER_FAIL);
                return;
            }
            pmdModel.initParam(0, 0, width, height, getFilesDir().toString());


        }catch (Exception e){
            e.printStackTrace();
            handler.sendEmptyMessage(MODEL_RENDER_FAIL);
        }


    }
    long lastTime = 0;
    long frame = 0;
    @Override
    public void onDrawFrame(GL10 gl10) {
        long currentTime = System.currentTimeMillis();
        if(pmdModel !=null) {
            pmdModel.render();
        }

    }






}
